package com.fucking.great.context.config;


import cn.hutool.cache.CacheUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alicp.jetcache.Cache;
import com.fucking.great.context.plun.CachePlug;
import com.fucking.great.context.plun.CachePlugFactory;
import com.fucking.great.context.plun.Plug;

import java.util.Map;

/**
 * Jetcache 门面缓存装饰模式。
 *
 */
public class JetcacheTxnConfigerDecorator extends AbstractTxnConfigerDecorator{
    public static final Log log = LogFactory.get();

    //
    private  final Cache<String, PathConfigBean>  PATH_CONFIG_CACHE ;
    private  final Cache<String, SystemConfigBean>  SYSTEM_CONFIG_CACHE ;
    private  final cn.hutool.cache.Cache<String, Plug> PLUGFACTORY_CACHE = CacheUtil.newFIFOCache(1000);

    public JetcacheTxnConfigerDecorator(TxnConfiger txnConfiger) {
        super(txnConfiger);
        log.info("正在使用Jetcache缓存配置,PathConfig配置的systemName=[jetcache-root-path],SystemConfig配置的systemName=[jetcache-root-system]");
        PATH_CONFIG_CACHE = (Cache<String, PathConfigBean>) initCache(txnConfiger,"jetcache-root-path");
        SYSTEM_CONFIG_CACHE = (Cache<String, SystemConfigBean>) initCache(txnConfiger,"jetcache-root-system");
    }
    /**
     * 获得Jetcache的缓存。
     * @param txnConfiger
     * @param systemName
     * @return
     */
    private Object initCache(TxnConfiger txnConfiger,String systemName) {
        Plug cachePlug = txnConfiger.getPlug(CachePlugFactory.PLUG_FACTORY_NAME, systemName);
        Map<String, Object> stringObjectMap = cachePlug.beginUser();
        Object cache = stringObjectMap.get(CachePlug.PLUN_NAME);
        return cache;
    }


    @Override
    public PathConfigBean getPathConfigBean(final String path) {
        return (PathConfigBean) PATH_CONFIG_CACHE.computeIfAbsent(path , (key) -> super.getPathConfigBean(key) );
    }

    @Override
    public SystemConfigBean getSystemConfigBean(final String systemName) {
        return (SystemConfigBean) SYSTEM_CONFIG_CACHE.computeIfAbsent(systemName , (key) -> super.getSystemConfigBean(key) );
    }

    @Override
    public Plug getPlug(String name, String systemName) {
        return PLUGFACTORY_CACHE.get(systemName+":"+name, () -> super.getPlug(name, systemName) );
    }
}
